<template>
  <el-drawer v-model="deawerObj.show" :title="deawerObj.title" ref="drawer">
    <el-tree
      :data="treeData.data"
      :props="defaultProps"
      node-key="id"
      show-checkbox
      highlight-current
      @check-change="handleCheckChange"
      ref="tree"
      default-expand-all
      :before-close="handleClose"
      :check-strictly="strictly"
    />

    <div class="btn">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="submit">授权</el-button>
    </div>
  </el-drawer>
</template>
<script>
import { defineComponent, reactive, ref } from "vue";
import { getTreeData, authData } from "@/api/role.js";
import { ElMessage } from "element-plus";
export default defineComponent({
  props: {
    deawerObj: {
      required: true,
      type: Object,
    },
  },
  setup(props, ctx) {
    //树形结构引用
    const tree = ref(null);

    //抽屉引用
    const drawer = ref(null);
    //用于存储树形结构数据、以及选中的数据
    const treeData = reactive({
      data: [],
    });
    //父子管理开关
    const strictly = ref(true);
    const defaultProps = {
      children: "children",
      label: "menuName",
    };
    const init = async () => {
      let roleId = props.deawerObj.roleId;
      if (roleId) {
        const { data, success } = await getTreeData(roleId);
        if (success) {
          let arr = data.currentNodeKey;
          treeData.data = data.tree;
          tree.value.setCheckedKeys(arr);
          strictly.value = false;
        }
      }
    };
    init();
    //树形结构选择方法 第一个参数： 对应的数据，第二个参数： 是否被选中，第三个节点： 子树是否有被选中
    const handleCheckChange = (data, checked, indeterminate) => {
      console.log(data, checked, indeterminate);
      //父节点： 全选，第二个参数为true，未全选： 第三个参数为true，第二个参数为false
    };
    const handleClose = (done) => {
      done();
    };
    //用于点击取消按钮，关闭抽屉
    const cancel = () => {
      drawer.value.handleClose();
    };
    //授权方法
    const submitData = async (arr) => {
      if (arr) {
        const { success } = await authData({
          roleId: props.deawerObj.roleId,
          menuIds: arr,
        });
        if (success) {
          ElMessage.success("授权成功！");
          drawer.value.handleClose();
        }
      }
    };
    const submit = () => {
      //获取到半选的id数组
      let middle = tree.value.getHalfCheckedKeys();
      //全选的id数组
      let all = tree.value.getCheckedKeys();
      all = all.concat(middle);
      if (all.length > 0) {
        submitData(all);
      }
    };
    return {
      strictly,
      drawer,
      tree,
      treeData,
      defaultProps,
      handleCheckChange,
      handleClose,
      cancel,
      submit,
    };
  },
});
</script>
<style lang="scss" scoped>
.el-tree {
  padding-left: 15px;
}
.btn {
  position: fixed;
  bottom: 5%;
  right: 5%;
}
.el-tree {
  margin-bottom: 5%;
}
</style>
